﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DXTools.UI.Modules.ODataQueryDesigner.Model;

namespace DXTools.UI.Modules.ODataQueryDesigner
{
    public class CodeGenerator
    {

        public CodeGenerator()
        {
        }

        public string BuildFunctionStub(EntityClass entity)
        {
            string functionStub = "RetrieveRecords : function(@Parameters)";
            string parameters = "";

            foreach (FilterClass item in entity.Filters)
            {
                switch (item.FilterOperator)
                {
                    case "Equals":
                    case "Does Not Equal":
                    case "Contains":
                    case "Does Not Contain":
                    case "Begins With":
                    case "Does Not Begin With":
                    case "Ends With":
                    case "Does Not End With":
                    case "Is Greater Than":
                    case "Is Greater That or Equal To":
                    case "On Or After":
                    case "Is Less Than":
                    case "Is Less Than or Equal To":
                    case "On Or Before":

                       if (String.IsNullOrEmpty(parameters))
                       {
                           parameters = item.SelectedAttribute.SchemaName;
                       }
                       else
                       {
                           parameters += ", " + item.SelectedAttribute.SchemaName;
                       }
                        break;
                    case "Contains Data":
                    case "Does Not Contain Data":
                        break;
                }

                
                
            }

            functionStub = functionStub.Replace("@Parameters", parameters);

            return functionStub;
           
        }


        public string GetAJAXRESTScriptFunctionAsText()
        {
            string script = String.Empty;

            Stream s = Application.GetResourceStream(new Uri("/DXTools.UI.Modules.ODataQueryDesigner;component/Resources/RESTQueryScriptJSON.js", UriKind.Relative)).Stream;
            using (StreamReader reader = new StreamReader(s))
            {
                script = reader.ReadToEnd();
            }

            return script;
        }
       
    }



/*
    if (typeof (SDK) == \"undefined\")
{ SDK = { __namespace: true }; }
// Namespace container for functions in this library.
SDK.RestEndpointPaging = {
 GetODataPath: function () {
  /// <summary>
  /// Utility function to retrieve the path to the REST endpoint.
  /// </summary>
  return Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";
 },
 RetrieveRecords: function (filter, callback) {
  this.parameterCheck(filter, "The SDK.RestEndpointPaging.RetrieveRecords function filter parameter is null or undefined.");
  this.parameterCheck(callback, "The SDK.RestEndpointPaging.RetrieveRecords function callback parameter is null or undefined.");
  /// <summary>
  /// Initiates an asynchronous request to retrieve records.
  /// If there are additional pages of records the SDK.RestEndpointPaging.RetrieveRecordsCallBack function will
  /// call this function.
  /// </summary>
  var retrieveRecordsReq = new XMLHttpRequest();
  retrieveRecordsReq.open("GET", SDK.RestEndpointPaging.GetODataPath() + filter, true);
  retrieveRecordsReq.setRequestHeader("Accept", "application/json");
  retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  retrieveRecordsReq.onreadystatechange = function () {
   /// <summary>
   /// This event handler passes the callback through
   /// </summary>
   SDK.RestEndpointPaging.RetrieveRecordsCallBack(this, callback);
  };
  retrieveRecordsReq.send();

 },
 RetrieveRecordsCallBack: function (retrieveRecordsReq, callback) {
  this.parameterCheck(retrieveRecordsReq, "The SDK.RestEndpointPaging.RetrieveRecordsCallBack function retrieveRecordsReq parameter is null or undefined.");
  this.parameterCheck(callback, "The SDK.RestEndpointPaging.RetrieveRecordsCallBack function callback parameter is null or undefined.");
  /// <summary>
  /// Handles the onreadystatechange event to process the records returned.
  /// If more pages are available this function will call the SDK.RestEndpointPaging.RetrieveRecords 
  /// function to get the rest.
  /// </summary>
  if (retrieveRecordsReq.readyState == 4 ) // complwrw
 {
   if (retrieveRecordsReq.status == 200) {
    //Success
    var retrievedRecords = JSON.parse(retrieveRecordsReq.responseText).d;
    /// The callback is called with the results.
    callback(retrievedRecords.results);

    if (null != retrievedRecords.__next) {
     // The existance of the '__next' property indicates that more records are available
     // So the originating function is called again using the filter value returned
     var filter = retrievedRecords.__next.replace(SDK.RestEndpointPaging.GetODataPath(), "");
     SDK.RestEndpointPaging.RetrieveRecords(filter, callback);
    }


   }
   else {
    //Failure
    SDK.RestEndpointPaging.errorHandler(retrieveRecordsReq);

   }
  }
 },
 //Function to handle any http errors
 errorHandler: function (XmlHttpRequest) {
  SDK.RestEndpointPaging.parameterCheck(XmlHttpRequest, "The SDK.RestEndpointPaging.errorHandler function XmlHttpRequest parameter is null or undefined.");
  /// <summary>
  /// Simply displays an alert message with details about any errors.
  /// </summary>
  alert("Error : " +
        XmlHttpRequest.status + ": " +
        XmlHttpRequest.statusText + ": " +
        JSON.parse(XmlHttpRequest.responseText).error.message.value);
 },
 parameterCheck: function (parameter, message) {
  if (parameter == null || (typeof parameter == "undefined"))
  { throw new Error(message); }
 },
 __namespace: true
};";

*/

}
